$(document).ready(function () {
    if ($("#tagsinput").length > 0) {
        $("#tagsinput").tagsinput({
            maxTags: 5,
            confirmKeys: [13, 44],
            maxChars: 10,
            trimValue: true
        });
    }
    if ($("#uploadImage").length > 0) {
        $("#uploadImage").fileinput({
            theme: 'fas',
            language: 'zh',
            minFileCount: 1, //最小上传文件数为1
            maxFileCount: 5, //最大上传文件数为5
            multiple: true //异步上传
        })
    }


    $(document).on('click', '#comm-submit', function () {
        var groupName = $("#groupName").val();
        var shortUrl = $("#shortUrl").val();
        if(!groupName) {
            alert("部落名称不能为空");
            return;
        }
        var formdata = new FormData();
        formdata.append("title", $("#title").val());
        formdata.append("columnId", $("#columnId").val());

        var uploadImage = $("#uploadImage");
        var files = uploadImage.length > 0 ? $("#uploadImage")[0].files : null;

        if (files && files.length > 0) {
            formdata.append("file", $("#uploadImage")[0].files[0]);
        }

        formdata.append("groupName", groupName);
        formdata.append("shortUrl", shortUrl);
        formdata.append("groupDesc", $("#groupDesc").val());
        // formdata.append("content", editor.txt.html());
        formdata.append("labelList", $("#tagsinput").val());
        formdata.append("iscomment", $("input[name='iscomment']:checked").val());
        formdata.append("iscommentshow", $("input[name='iscommentshow']:checked").val());
        formdata.append("score", $("#score").val());
        formdata.append("groupId", $("#groupId").val());

        $.ajax({
            url: '/user/group/create',
            type: 'post',
            data: formdata,
            cache: false,
            processData: false,
            contentType: false,
            success: function (data) {
                if (data.code == 200) {
                    layer.msg("发布成功", {shift: -1}, function () {
                        return location.href = "/topic/" + data.data;
                    });
                } else {
                    alert(data.msg);
                }
            },
            error: function () {
                console.log('请求出错！');
            }
        })
    });

    $(document).on('click', '#update-submit', function () {
        var formdata = new FormData();
        formdata.append("id", $("#id").val());
        formdata.append("title", $("#title").val());
        formdata.append("columnId", $("#columnId").val());
        if ($("#uploadImage")[0].files[0] != undefined) {
            formdata.append("file", $("#uploadImage")[0].files[0]);
        }
        formdata.append("content", editor.txt.html());
        formdata.append("labelList", $("#tagsinput").val());
        formdata.append("iscomment", $("input[name='iscomment']:checked").val());
        formdata.append("iscommentshow", $("input[name='iscommentshow']:checked").val());
        formdata.append("score", $("#score").val());
        formdata.append("groupId", $("#groupId").val());

        $.ajax({
            url: '/user/topic/update',
            type: 'post',
            data: formdata,
            cache: false,
            processData: false,
            contentType: false,
            success: function (data) {
                if (data.code == 200) {
                    layer.msg("更新成功", {shift: -1}, function () {
                        location.href = "/topic/" + data.data;
                        return
                    });
                } else {
                    alert(data.msg);
                }
            },
            error: function () {
                console.log('请求出错！');
            }
        })
    });

    $(document).on('click', '#delete-topic', function () {
        var id = $(this).attr("data-id");
        layer.confirm('您是确定删除本条话题？！', {
            btn: ['确定', '取消'] //按钮
        }, function () {
            $.ajax({
                url: "/user/topic/delete?" + Math.random(),
                data: {"id": id},
                dataType: "json",
                type: "POST",
                cache: false,
                async: false,
                error: function (i, g, h) {
                    layer.msg('发送错误', {icon: 2});
                },
                success: function (ret) {
                    if (ret.code >= 0) {
                        layer.msg("删除成功！", {icon: 1});
                        location.href = ret.data;
                        return false;
                    } else {
                        layer.msg(ret.message, {icon: 5});
                        return false;
                    }
                }
            });
        }, function () {
        });
    });

    $(document).on('click', '#father-comment', function () {
        var topicId = $("#topicId").val(), content = editor.txt.html(),
            ispublic = $('input[name="ispublic"]:checked').val();
        $.ajax({
            url: '/user/add/topic/comment',
            type: 'post',
            data: {'topicId': topicId, "content": content, "ispublic": ispublic},
            dataType: 'json',
            success: function (data) {
                if (data.code == 200) {
                    layer.msg("发布成功", {shift: -1}, function () {
                        location.href = "/topic/" + data.data;
                    });
                } else {
                    alert(data.msg);
                }
            },
            error: function () {
                console.log('请求出错！');
            }
        })
    });

    $(".commentOpen").click(function () {
        $.ajax({
            url: '/user/status',
            type: 'post',
            async: false,
            dataType: 'json',
            success: function (data) {
                if (data.code == 200) {
                    if (data.data.userLogin == 1) {
                        $(this).hide();
                        $(this).parent().next().show();
                    } else {
                        layer.msg("请登录后再发表评论", {icon: 2});
                        return false;
                    }
                }
            }
        });

    });

    //从缓存中获取数据并渲染
    let msgBoxList = JSON.parse(window.localStorage.getItem('msgBoxList')) || [];
    innerHTMl(msgBoxList)

    //点击小图片，显示表情
    $(document).on('click', '.imgBtn', function (e) {
        if (!$(this).parent().children(".face").length > 0) {
            //不含子元素
            $(this).parent().append(
                "<div class=\"face\">\n" +
                "    <ul>\n" +
                "        <li><img src=\"/default/images/facebox/1.gif\" title=\"[呵呵]\"></li>\n" +
                "        <li><img src=\"/default/images/facebox/2.gif\" title=\"[嘻嘻]\"></li>\n" +
                "        <li><img src=\"/default/images/facebox/3.gif\" title=\"[哈哈]\"></li>\n" +
                "        <li><img src=\"/default/images/facebox/4.gif\" title=\"[可爱]\"></li>\n" +
                "        <li><img src=\"/default/images/facebox/5.gif\" title=\"[可怜]\"></li>\n" +
                "        <li><img src=\"/default/images/facebox/6.gif\" title=\"[挖鼻屎]\"></li>\n" +
                "        <li><img src=\"/default/images/facebox/7.gif\" title=\"[吃惊]\"></li>\n" +
                "        <li><img src=\"/default/images/facebox/8.gif\" title=\"[害羞]\"></li>\n" +
                "        <li><img src=\"/default/images/facebox/9.gif\" title=\"[挤眼]\"></li>\n" +
                "        <li><img src=\"/default/images/facebox/10.gif\" title=\"[闭嘴]\"></li>\n" +
                "        <li><img src=\"/default/images/facebox/11.gif\" title=\"[鄙视]\"></li>\n" +
                "        <li><img src=\"/default/images/facebox/12.gif\" title=\"[爱你]\"></li>\n" +
                "        <li><img src=\"/default/images/facebox/13.gif\" title=\"[泪]\"></li>\n" +
                "        <li><img src=\"/default/images/facebox/14.gif\" title=\"[偷笑]\"></li>\n" +
                "        <li><img src=\"/default/images/facebox/15.gif\" title=\"[亲亲]\"></li>\n" +
                "        <li><img src=\"/default/images/facebox/16.gif\" title=\"[生病]\"></li>\n" +
                "        <li><img src=\"/default/images/facebox/17.gif\" title=\"[太开心]\"></li>\n" +
                "        <li><img src=\"/default/images/facebox/18.gif\" title=\"[懒得理你]\"></li>\n" +
                "        <li><img src=\"/default/images/facebox/19.gif\" title=\"[右哼哼]\"></li>\n" +
                "        <li><img src=\"/default/images/facebox/20.gif\" title=\"[左哼哼]\"></li>\n" +
                "        <li><img src=\"/default/images/facebox/21.gif\" title=\"[嘘]\"></li>\n" +
                "        <li><img src=\"/default/images/facebox/22.gif\" title=\"[衰]\"></li>\n" +
                "        <li><img src=\"/default/images/facebox/23.gif\" title=\"[委屈]\"></li>\n" +
                "        <li><img src=\"/default/images/facebox/24.gif\" title=\"[吐]\"></li>\n" +
                "        <li><img src=\"/default/images/facebox/25.gif\" title=\"[打哈气]\"></li>\n" +
                "        <li><img src=\"/default/images/facebox/26.gif\" title=\"[抱抱]\"></li>\n" +
                "        <li><img src=\"/default/images/facebox/27.gif\" title=\"[怒]\"></li>\n" +
                "        <li><img src=\"/default/images/facebox/28.gif\" title=\"[疑问]\"></li>\n" +
                "        <li><img src=\"/default/images/facebox/29.gif\" title=\"[馋嘴]\"></li>\n" +
                "        <li><img src=\"/default/images/facebox/30.gif\" title=\"[拜拜]\"></li>\n" +
                "        <li><img src=\"/default/images/facebox/31.gif\" title=\"[思考]\"></li>\n" +
                "        <li><img src=\"/default/images/facebox/32.gif\" title=\"[汗]\"></li>\n" +
                "        <li><img src=\"/default/images/facebox/33.gif\" title=\"[困]\"></li>\n" +
                "        <li><img src=\"/default/images/facebox/34.gif\" title=\"[睡觉]\"></li>\n" +
                "        <li><img src=\"/default/images/facebox/35.gif\" title=\"[钱]\"></li>\n" +
                "        <li><img src=\"/default/images/facebox/36.gif\" title=\"[失望]\"></li>\n" +
                "        <li><img src=\"/default/images/facebox/37.gif\" title=\"[酷]\"></li>\n" +
                "        <li><img src=\"/default/images/facebox/38.gif\" title=\"[花心]\"></li>\n" +
                "        <li><img src=\"/default/images/facebox/39.gif\" title=\"[哼]\"></li>\n" +
                "        <li><img src=\"/default/images/facebox/40.gif\" title=\"[鼓掌]\"></li>\n" +
                "        <li><img src=\"/default/images/facebox/41.gif\" title=\"[晕]\"></li>\n" +
                "        <li><img src=\"/default/images/facebox/42.gif\" title=\"[悲伤]\"></li>\n" +
                "        <li><img src=\"/default/images/facebox/43.gif\" title=\"[抓狂]\"></li>\n" +
                "        <li><img src=\"/default/images/facebox/44.gif\" title=\"[黑线]\"></li>\n" +
                "        <li><img src=\"/default/images/facebox/45.gif\" title=\"[阴险]\"></li>\n" +
                "        <li><img src=\"/default/images/facebox/46.gif\" title=\"[怒骂]\"></li>\n" +
                "        <li><img src=\"/default/images/facebox/47.gif\" title=\"[心]\"></li>\n" +
                "        <li><img src=\"/default/images/facebox/48.gif\" title=\"[伤心]\"></li>\n" +
                "        <li><img src=\"/default/images/facebox/49.gif\" title=\"[猪头]\"></li>\n" +
                "        <li><img src=\"/default/images/facebox/50.gif\" title=\"[ok]\"></li>\n" +
                "        <li><img src=\"/default/images/facebox/51.gif\" title=\"[耶]\"></li>\n" +
                "        <li><img src=\"/default/images/facebox/52.gif\" title=\"[good]\"></li>\n" +
                "        <li><img src=\"/default/images/facebox/53.gif\" title=\"[不要]\"></li>\n" +
                "        <li><img src=\"/default/images/facebox/54.gif\" title=\"[赞]\"></li>\n" +
                "        <li><img src=\"/default/images/facebox/55.gif\" title=\"[来]\"></li>\n" +
                "        <li><img src=\"/default/images/facebox/56.gif\" title=\"[弱]\"></li>\n" +
                "        <li><img src=\"/default/images/facebox/57.gif\" title=\"[蜡烛]\"></li>\n" +
                "        <li><img src=\"/default/images/facebox/58.gif\" title=\"[钟]\"></li>\n" +
                "        <li><img src=\"/default/images/facebox/59.gif\" title=\"[蛋糕]\"></li>\n" +
                "        <li><img src=\"/default/images/facebox/60.gif\" title=\"[话筒]\"></li>\n" +
                "        <li><img src=\"/default/images/facebox/61.gif\" title=\"[围脖]\"></li>\n" +
                "        <li><img src=\"/default/images/facebox/62.gif\" title=\"[转发]\"></li>\n" +
                "        <li><img src=\"/default/images/facebox/63.gif\" title=\"[路过这儿]\"></li>\n" +
                "        <li><img src=\"/default/images/facebox/64.gif\" title=\"[变脸]\"></li>\n" +
                "        <li><img src=\"/default/images/facebox/65.gif\" title=\"[困]\"></li>\n" +
                "        <li><img src=\"/default/images/facebox/66.gif\" title=\"[生闷气]\"></li>\n" +
                "        <li><img src=\"/default/images/facebox/67.gif\" title=\"[不要啊]\"></li>\n" +
                "        <li><img src=\"/default/images/facebox/68.gif\" title=\"[泪奔]\"></li>\n" +
                "        <li><img src=\"/default/images/facebox/69.gif\" title=\"[运气中]\"></li>\n" +
                "        <li><img src=\"/default/images/facebox/70.gif\" title=\"[有钱]\"></li>\n" +
                "    </ul>\n" +
                "</div>")
        }

        $(this).parent().children(".face").slideDown(); //慢慢向下展开
        e.stopPropagation(); //阻止冒泡事件
    });

    //在桌面任意地方点击，关闭表情框
    $(document).click(function () {
        $(".face").slideUp(); //慢慢向上收
    });

    //点击小图标时，添加功能
    $(document).on('click', '.face ul li', function () {
        let simg = $(this).find("img").clone();
        $(this).parent().parent().parent().parent().children(".message").append(simg); //将表情添加到输入框
        var txt = $(this).parent().parent().parent().parent().children(".message").html();
        if (txt.length > 0) {
            $(this).parent().parent().parent().parent().children(".placeholder").hide();
        } else {
            $(this).parent().parent().parent().parent().children(".placeholder").show();
        }
    });

    //点击发表按扭，发表内容
    $(document).on('click', '.comment-submit', function () {
        var commentId = $(this).attr("data-comment-id");
        let txt = $(this).parent().parent().parent().children(".message").html(); //获取输入框内容
        if (!txt) {
            $('.message').focus(); //自动获取焦点
            return;
        }
        let obj = {
            msg: txt
        }
        $.ajax({
            url: '/user/add/topic/reply',
            type: 'post',
            data: {'commentId': commentId, "content": txt},
            dataType: 'json',
            success: function (data) {
                if (data.code == 200) {
                    layer.msg("发布成功", {shift: -1}, function () {
                        location.href = "/topic/" + data.data;
                    });
                } else {
                    alert(data.msg);
                }
            },
            error: function () {
                console.log('请求出错！');
            }
        })
        msgBoxList.unshift(obj) //添加到数组里
        window.localStorage.setItem('msgBoxList', JSON.stringify(msgBoxList)) //将数据保存到缓存
        innerHTMl([obj]) //渲染当前输入框内容
        $('.message').html('') // 清空输入框
    });

    $(document).on('focus', '.aw-comment-box-main', function () {
        $(".aw-comment-box-btn").hide();
        $(this).children(".aw-comment-box-btn").show();
    });

    $(document).on('click', '.placeholder', function () {
        $(".aw-comment-box-btn").hide();
        $(this).parent().children(".aw-comment-box-btn").show();
        $(this).next().focus();
    });

    $(document).on('keyup', '.message', function () {
        var txt = $(this).html();
        if (txt.length > 0) {
            $(this).prev(".placeholder").hide();
        } else {
            $(this).prev(".placeholder").show();
        }
    });

    $(document).on('click', '.close-comment-box', function () {
        $(this).parent().parent().hide();
    });

    $(document).on('click', '.re-comment', function () {
        var commentId = $(this).attr("data-comment-id");
        var nickname = $(this).attr("data-nickname");
        $(this).parent().parent().parent().parent().parent().parent().next().children().children().children().children(".comment-submit").attr("data-comment-id", commentId);
        $(this).parent().parent().parent().parent().parent().parent().next().children().children(".placeholder").html(nickname);

    });

    $(document).on('click', '.aw-add-comment', function () {
        if ($(this).hasClass("active")) {
            $(this).removeClass('active');
            if (!$(this).parent().parent().parent().children().children().children().children("li").length > 0) {
                $(this).parent().parent().parent().children(".box-comment").hide();
            }
            return;
        }
        $.each($(".aw-comment-list"), function (i, v) {
            if (!$(v).children().children("li").length > 0) {
                $(v).parent().hide();
            }
        })

        var commentId = $(this).attr("data-comment-id");
        $.ajax({
            url: '/user/status',
            type: 'post',
            async: false,
            dataType: 'json',
            success: function (data) {
                if (data.code == 200) {
                    if (data.data.userLogin == 1) {
                        if (!$(this).parent().parent().parent().children().children(".aw-comment-box-form").length > 0) {
                            //不含子元素
                            $(this).parent().parent().parent().children(".box-comment").append(
                                "<div class=\"aw-comment-box-form\">\n" +
                                "    <div class=\"aw-comment-box-main\">\n" +
                                "       <div class=\"placeholder\" style=\"display:block;\">评论一下...</div>\n" +
                                "       <div class=\"form-control message\" contenteditable=\"true\"></div>\n" +
                                "          <div class=\"aw-comment-box-btn But\" style=\"display: block;\">\n" +
                                "               <a class=\"imgBtn\" href=\"javascript:void(0);\"></a>\n" +
                                "               <span class=\"pull-right\">\n" +
                                "                    <a href=\"javascript:;\" class=\"btn btn-mini btn-success comment-submit\" data-comment-id=\"" + commentId + "\">评论</a>\n" +
                                "                    <a href=\"javascript:;\" class=\"btn btn-mini btn-gray close-comment-box\">取消</a>\n" +
                                "               </span>\n" +
                                "          </div>\n" +
                                "     </div>\n" +
                                "</div>"
                            )
                        } else {
                            $(this).parent().parent().parent().children().children().children().children().children().children(".comment-submit").attr("data-comment-id", commentId);
                        }
                        $(".aw-add-comment").removeClass('active');
                        $(this).addClass('active');
                        $(".aw-comment-box-btn").hide();
                        $(this).parent().parent().parent().children(".box-comment").show();
                    } else {
                        layer.msg("请登录后再发表评论", {icon: 2});
                        return false;
                    }
                }
            }.bind(this)
        });
    });

    //删除当前数据
    $("body").on('click', '.del', function () {
        let index = $(this).parent().parent().index();
        msgBoxList.splice(index, 1)
        window.localStorage.setItem('msgBoxList', JSON.stringify(msgBoxList)) //将数据保存到缓存
        $(this).parent().parent().remove()
    })

    //渲染html
    function innerHTMl(List) {
        List = List || []
        List.forEach(item => {
            let str =
                `<div class='msgBox'>
						<div class="headUrl">
							<img src='images/tx.jpg' width='50' height='50'/>
							<div>
								<span class="title">木林森里没有木</span>
								<span class="time">2018-01-01</span>
							</div>
							<a class="del">删除</a>
						</div>
						<div class='msgTxt'>
							${item.msg}
						</div>
					</div>`
            $(".msgCon").prepend(str);
        })
    }
});